using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using HttpWrapper;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ForwardingHttpCall>();
builder.Services.AddHttpClient();

var app = builder.Build();

app.UseDeveloperExceptionPage();

app.UseMiddleware<MapHttpCallMiddleware>();

/// <summary>
/// ����һ��form�ļ�����ת��Ϊ����������
/// </summary>
app.MapMethods("form2bin", new[] { "post", "put" }, async ([FromServices] ForwardingHttpCall call, HttpRequest req) =>
{
    if(!req.HasFormContentType)
    {
        return Results.StatusCode(415);
    }

    var files = req.Form.Files;
    if(files.Count == 0)
    {
        return Results.BadRequest("missing file");
    }

    var file = req.Form.Files[0];
    var request = call.Request!;
    request.Content = new StreamContent(file.OpenReadStream());
    foreach(var header in file.Headers)
    {
        request.Content.Headers.TryAddWithoutValidation(header.Key, header.Value as IEnumerable<string?>);
    }
    await call.SendAsync();
    return Results.Ok();
});

app.MapMethods("base642bin", new[] { "post", "put" }, async ([FromServices] ForwardingHttpCall call, HttpRequest req) =>
{
    if(!req.HasJsonContentType())
    {
        return Results.StatusCode(415);
    }

    var json = await req.ReadFromJsonAsync<Base64Request>();
    if(json is null)
    {
        return Results.BadRequest();
    }

    var buffer = Convert.FromBase64String(json.File);
    var request = call.Request!;
    var file = new MemoryStream(buffer);
    request.Content = new StreamContent(file);
    request.Content.Headers.ContentType = new MediaTypeHeaderValue(json.Type);
    await call.SendAsync();
    return Results.Ok();
});

/// <summary>
/// ��������Ӧ��status code�Լ�body��װ��body�ڣ�����״̬��ͳһ�޸�Ϊ200
/// </summary>
app.MapMethods("inner-status", new[] { "get", "post", "put", "patch", "delete" }, async ([FromServices] ForwardingHttpCall call) =>
{
    var response = await call.SendAsync();
    if(response.Content.Headers.ContentType?.MediaType == "application/json")
    {
        var body = await JsonSerializer.DeserializeAsync<JsonElement>(await response.Content.ReadAsStreamAsync());
        var newResult = new
        {
            code = response.StatusCode,
            data = body
        };
        response.StatusCode = System.Net.HttpStatusCode.OK;
        response.Content = new StringContent(JsonSerializer.Serialize(newResult), Encoding.UTF8, "application/json");
    }
});

app.Run();

record Base64Request(string Type, string File);
